/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import fs from 'fs';
import fse from 'fs-extra';
import path from 'path';

import { PathUtil } from '../../common/util/path-util.js';
import { HvigorLogger } from '../log/hvigor-log.js';

import { JsonReader } from './json-reader.js';

const logger = HvigorLogger.getLogger('meta-util');

const hvigorVersion = 'hvigorVersion';

function getMetaCacheFilePath() {
  return path.resolve(PathUtil.getHvigorCacheDir(logger), './cache/meta.json');
}

export function getMetaProperty(property: string) {
  const metaCacheFilePath = getMetaCacheFilePath();
  return fs.existsSync(metaCacheFilePath) ? JsonReader.getJsonObj(metaCacheFilePath)[property] : undefined;
}

export function updateMetaProperties(metaInfo: Map<string, string | undefined>) {
  if (!metaInfo.size) {
    return;
  }
  const metaCacheFilePath = getMetaCacheFilePath();
  const meta = fs.existsSync(metaCacheFilePath) ? JsonReader.getJsonObj(metaCacheFilePath) : {};
  metaInfo.forEach((value, property) => (meta[property] = value));
  fse.ensureFileSync(metaCacheFilePath);
  fse.writeJSONSync(metaCacheFilePath, meta);
}

export function getLastHvigorVersion(): string | undefined {
  return getMetaProperty(hvigorVersion);
}
